package com.test.schoolhelper.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;

import com.test.schoolhelper.R;
import com.test.schoolhelper.base.BaseActivity;
import com.test.schoolhelper.databinding.ActivityCalculatorBinding;
import com.test.schoolhelper.utils.Calculate;
import com.test.schoolhelper.utils.InputItem;
import com.test.schoolhelper.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

// TODO: 2024/5/31
public class CalculatorActivity extends BaseActivity<ActivityCalculatorBinding> implements View.OnClickListener {

    protected List<InputItem> inputList; //定义记录每次输入的数
    protected String lastResult;
    protected CurrentStatus currentStatus = CurrentStatus.INIT;

    public static enum CurrentStatus {
        INIT, CALCU, END, ERROR
    }

    @Override
    protected void initData() {
        super.initData();
        inputList = new ArrayList<>();
        lastResult = "";
        initInput();

        getBinding().hsV2.setOnTouchListener((arg0, arg1) -> {
            //不能滑动
            return true;
            //可以滑动
            //return false;
        });
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().ivBack.setOnClickListener(this);

        getBinding().ivZero.setOnClickListener(this);
        getBinding().ivOne.setOnClickListener(this);
        getBinding().ivTwo.setOnClickListener(this);
        getBinding().ivThree.setOnClickListener(this);
        getBinding().ivFour.setOnClickListener(this);
        getBinding().ivFive.setOnClickListener(this);
        getBinding().ivSix.setOnClickListener(this);
        getBinding().ivSeven.setOnClickListener(this);
        getBinding().ivEight.setOnClickListener(this);
        getBinding().ivNine.setOnClickListener(this);

        getBinding().ivPlus.setOnClickListener(this);//加
        getBinding().ivDivide.setOnClickListener(this);//除
        getBinding().ivTimes.setOnClickListener(this);//乘
        getBinding().ivMinus.setOnClickListener(this);//减
        getBinding().ivEqual.setOnClickListener(this);
        getBinding().ivPoint.setOnClickListener(this);
        getBinding().ivClear.setOnClickListener(this);
        getBinding().ivDelete.setOnClickListener(this);
        getBinding().ivPercent.setOnClickListener(this);

        getBinding().tvStandard2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count >= 12) {
                    //启用滑动
                    getBinding().hsV2.setOnTouchListener((arg0, arg1) -> {
                        //能滑动
                        return false;
                    });
                    if (count % 2 == 0 && count <= 20) {
                        getBinding().tvStandard2.setTextSize(43 - count + 3);
                    }

                    getBinding().hsV2.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getBinding().hsV2.fullScroll(HorizontalScrollView.FOCUS_RIGHT);//主线程
                        }
                    }, 25);

                } else {
                    getBinding().tvStandard2.setTextSize(43);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_calculator;
    }

    @Override
    protected ActivityCalculatorBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityCalculatorBinding.inflate(layoutInflater);
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_zero:
                inputNum(view);
                break;
            case R.id.iv_one:
                inputNum(view);
                break;
            case R.id.iv_two:
                inputNum(view);
                break;
            case R.id.iv_three:
                inputNum(view);
                break;
            case R.id.iv_four:
                inputNum(view);
                break;
            case R.id.iv_five:
                inputNum(view);
                break;
            case R.id.iv_six:
                inputNum(view);
                break;
            case R.id.iv_seven:
                inputNum(view);
                break;
            case R.id.iv_eight:
                inputNum(view);
                break;
            case R.id.iv_nine:
                inputNum(view);
                break;
            case R.id.iv_plus://加
                inputOpe(view);
                break;
            case R.id.iv_minus://减
                inputOpe(view);
                break;
            case R.id.iv_times://乘
                inputOpe(view);
                break;
            case R.id.iv_divide://除
                inputOpe(view);
                break;
            case R.id.iv_equal:
                getResult(view);
                break;
            case R.id.iv_percent:
                inputOpeOpe(view);
                break;
            case R.id.iv_clear:
                clear();
                break;
            case R.id.iv_delete:
                delete();
                break;
            case R.id.iv_point:
                inputNum(view);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    protected void clear() {
        if (!isInitInputList()) {
            initInput();
        } else {
            getBinding().tvStandard1.setText("");
        }
    }

    protected void delete() {
        if (!isInitInputList()) {
            if (inputList.size() == 1) {
                initInput();
            } else {
                subInputListAndInputTV().getValue();
            }
        }
    }

    protected boolean isInitInputList() {         //判断是否是初始状态
        if (inputList.size() == 1 && inputList.get(0).getValue().equals(getBinding().ivZero.getTag().toString())) {
            getBinding().tvStandard2.setTextColor(getResources().getColor(R.color.text_input));
            return true;
        }
        return false;
    }

    protected void initInput() {
        inputList.clear();
        inputList.add(new InputItem(getBinding().ivZero.getTag().toString(), InputItem.TYPE.NUM));
        getBinding().tvStandard2.setText(getBinding().ivZero.getTag().toString());
        getBinding().tvStandard1.setText("");
        currentStatus = CurrentStatus.INIT;
    }

    protected void addTV(View view) {
        getBinding().tvStandard2.setText(getBinding().tvStandard2.getText() + view.getTag().toString());
    }

    protected String updateInputTV() {
        String inputString = "";
        for (InputItem inputItem : inputList) {
            inputString += inputItem.getValue();
        }
        getBinding().tvStandard2.setText(inputString);
        return inputString;
    }

    protected InputItem subInputListAndInputTV() {
        if (inputList.size() > 0) {
            InputItem inputItem = inputList.remove(inputList.size() - 1);
            updateInputTV();
            return inputItem;
        }
        return null;
    }

    protected InputItem getLastInputItem() {
        if (inputList.size() > 0) {
            return inputList.get(inputList.size() - 1);
        }
        return null;
    }

    protected void inputOpe(View view) {
        if (getLastInputItem().getType() == InputItem.TYPE.OPE) {    //连续输入两个OPR型操作符，删除第一个
            subInputListAndInputTV().getValue();
        }
        inputList.add(new InputItem(view.getTag().toString(), InputItem.TYPE.OPE));
        addTV(view);
    }

    protected void inputOpeOpe(View view) {
        if (getLastInputItem().getType() != InputItem.TYPE.NUM                      //OPT_OPT前必须是数字或右括号
                && getLastInputItem().getType() != InputItem.TYPE.RIGHT_BRACKET) {
            getLastInputItem().getValue();
            return;
        }
        inputList.add(new InputItem(view.getTag().toString(), InputItem.TYPE.OPE_OPE));
        addTV(view);
    }

    protected void inputNum(View view) {
        inputNum(view.getTag().toString());
    }

    protected void inputNum(String num) {
        initEndStatus();           //处理上次运算结束的情况
        if (getLastInputItem().getType() == InputItem.TYPE.OPE_NUM) {
            inputOpe(getBinding().ivTimes);
        }
        if (isInitInputList() && (!num.equals("."))) {      //初始状态下输入数字替换原始0，小数点不替换
            subInputListAndInputTV().getValue();
        }
        if (num.equals(".")) {       //限制一个数中最多只有一个小数点
            for (int i = inputList.size() - 1; i > 0; i--) {
                if (inputList.get(i).getType() != InputItem.TYPE.NUM) {
                    break;
                } else if (inputList.get(i).getValue().equals(getBinding().ivPoint.getTag().toString())) {
                    return;
                }
            }
        }
        inputList.add(new InputItem(num, InputItem.TYPE.NUM));
        getBinding().tvStandard2.setText(getBinding().tvStandard2.getText() + num);

    }

    protected void initEndStatus() {    //上次计算结束后，初始化input
        if (currentStatus == CurrentStatus.END && getLastInputItem().getType() == InputItem.TYPE.NUM) {
            getBinding().tvStandard1.setText(String.valueOf(getBinding().tvStandard1.getText()) + getBinding().tvStandard2.getText());
            initInput();
        }
        currentStatus = CurrentStatus.CALCU;
    }

    protected void getResult(View view) {
        if (getBinding().tvStandard2.getText().charAt(getBinding().tvStandard2.length() - 1) != '=') {
            addTV(view);
        }
        String res = "";
        try {
            res = Calculate.getResult(inputList, this);    //取得计算结果
            resultManage(res);       //处理界面显示信息
            getBinding().tvStandard2.setTextColor(getResources().getColor(R.color.text_result));
        } catch (ArithmeticException e) {
            res = "0不能做除数！";
            ToastUtils.getInstance().show(this, res);
        } catch (Exception e) {
            Log.e("ling", "e:=" + e);
            res = "算术式不正确！";
            ToastUtils.getInstance().show(this, res);
        }
    }

    protected void resultManage(String result) {
        getBinding().tvStandard1.setText(getBinding().tvStandard2.getText());
        getBinding().hsV1.fullScroll(HorizontalScrollView.FOCUS_RIGHT);//设置滑动显示最右侧
        getBinding().tvStandard2.setText(result);

        inputList.clear();
        lastResult = result;
        for (char c : result.toCharArray()) {
            inputList.add(new InputItem(String.valueOf(c), InputItem.TYPE.NUM));
        }
        currentStatus = CurrentStatus.END;
    }

}